import React, { useState, useEffect } from 'react';
import { Modal, Upload, Button, Progress, message } from 'antd';
import { InboxOutlined, DownloadOutlined } from '@ant-design/icons';
import { gisDataAreaFileImport } from '../../api/gis';

interface DataAreaBatchUploadModalProps {
  visible: boolean;
  onCancel: () => void;
  planetId: number;
  treeUuid: string;
  onSuccess?: () => void;
}

const DataAreaBatchUploadModal: React.FC<DataAreaBatchUploadModalProps> = ({ 
  visible, 
  onCancel, 
  planetId, 
  treeUuid,
  onSuccess 
}) => {
  const [fileList, setFileList] = useState<any[]>([]);
  const [uploading, setUploading] = useState(false);

  useEffect(() => {
    if (visible) {
      setFileList([]);
    }
  }, [visible]);


  const handleUpload = async (files: any[]) => {
    if (!planetId) {
      message.error('星球ID不能为空');
      return;
    }

    if (files.length === 0) {
      message.warning('请先选择要上传的文件');
      return;
    }

    setUploading(true);
    let successCount = 0;
    let failCount = 0;
    let totalCount = 0;
    const errors: string[] = [];

    for (const file of files) {
      try {
        const result = await uploadSingleFile(file);
        successCount += result.success_count || 0;
        failCount += result.fail_count || 0;
        totalCount += result.total_count || 0;
        if (result.errors) {
          errors.push(...result.errors);
        }
      } catch (error) {
        console.error('Upload error:', error);
        message.error(error?.message || '上传失败');
        failCount++;
      }
    }

    if (successCount > 0) {
      message.success(`成功上传 ${successCount} 条数据区域数据`);
      if (failCount > 0) {
        message.warning(`${failCount} 条数据上传失败`);
      }
      if (errors.length > 0) {
        console.error('上传错误详情:', errors);
      }
      setFileList([]);
      onSuccess?.();
      onCancel();
    } else {
      message.error('文件上传失败');
    }
    setUploading(false);
  };

  const customRequest = async (options: any) => {
    const { file, onSuccess: uploadOnSuccess, onError, onProgress } = options;
    
    try {
      const response = await gisDataAreaFileImport({
        file,
        planet_id: planetId,
        tree_uuid: treeUuid
      });
      
      if (response.code === 200) {
        uploadOnSuccess(response.data, file);
        message.success(`上传成功`);
        // 调用传入的onSuccess回调来刷新列表
        onSuccess?.();
        onCancel();
      } else {
        message.error(response.msg);
        onError({ msg: response.msg || '上传失败', response: response });
      }
    } catch (err: any) {
      message.error(err?.message || '网络错误');
      onError({ msg: '网络错误', response: err });
    }
  };

  const handleFileChange = (info: any) => {
    let files = [...info.fileList];
    files = files.slice(-1); // 只允许上传一个文件
    setFileList(files);
  };

  const handleFileRemove = (file: any) => {
    setFileList((prev) => prev.filter((item) => item.uid !== file.uid));
  };

  // 下载模版文件
  const downloadTemplate = () => {
    // 创建下载链接
    const link = document.createElement('a');
    link.href = '/data_area.xlsx'; // 指向public目录下的Excel文件
    link.download = '数据区域导入模版.xlsx'; // 设置下载文件名
    link.style.visibility = 'hidden';
    
    // 添加到DOM并触发下载
    document.body.appendChild(link);
    link.click();
    
    // 清理DOM
    document.body.removeChild(link);
  };

  return (
    <Modal 
      title="批量导入数据区域" 
      open={visible} 
      onCancel={onCancel} 
      footer={null} 
      width={600} 
      centered 
      destroyOnHidden
    >
      <div style={{ display: 'flex', alignItems: 'flex-start' }}>
        <div style={{ width: 100, fontSize: 18, marginTop: 16 }}>批量导入：</div>
        <div style={{ flex: 1 }}>
          <div style={{ marginBottom: 16 }}>
            <Button 
              type="link" 
              icon={<DownloadOutlined />} 
              onClick={downloadTemplate}
              style={{ padding: 0 }}
            >
              下载Excel模版
            </Button>
          </div>
          
          <Upload.Dragger
            multiple={false}
            fileList={fileList}
            onChange={handleFileChange}
            onRemove={handleFileRemove}
            accept=".xlsx,.xls"
            style={{ marginBottom: 16 }}
            customRequest={customRequest}
            data={{
              planet_id: planetId
            }}
            headers={{
              token: localStorage.getItem('token') || ''
            }}
          >
            <p className="ant-upload-drag-icon">
              <InboxOutlined style={{ fontSize: 48, color: '#1890ff' }} />
            </p>
            <p>
              将文件拖到此处或点击上传
              <br />
              支持 .xlsx、.xls 格式文件
            </p>
          </Upload.Dragger>
          
          <div style={{ textAlign: 'center', marginTop: 24 }}>
            <Button onClick={onCancel}>关闭</Button>
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default DataAreaBatchUploadModal; 